from LLDs import get_LLDs_dataset_casia
import torch
from torch import nn
import utils
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class LinearNetwork(nn.Module):

    def __init__(self):
        super(LinearNetwork, self).__init__()

        self.linear_relu_stack = nn.Sequential(
            nn.Linear(6373,4096),
            nn.Dropout(0.6),
	        nn.ReLU(),
            nn.Linear(4096,4096),
            nn.Dropout(0.6),
            nn.ReLU(),
            nn.Linear(4096, 2048),
            nn.Dropout(0.6),
            nn.ReLU(),
            nn.Linear(2048,6),
            nn.Softmax(dim=1)
            # nn.Linear(6373, 4096),
            # nn.ReLU(),
            # nn.Dropout(p=0.5),
            # nn.Linear(4096, 512),
            # nn.ReLU(),
            # nn.Dropout(p=0.5),
            # nn.Linear(512, 6),
            # nn.Softmax()
        )

    def forward(self, x):

        logits = self.linear_relu_stack(x)

        return logits

def train_loop(dataloader, model, loss_fn, optimizer):
    for batch, (X, y) in enumerate(dataloader):
        # Compute prediction and loss
        X = X.to(device)
        pred = model(X)
        y = y.to(device)
        pred = pred.to(device)
        loss = loss_fn(pred, y)

        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()


def test_loop(dataloader, model, loss_fn):
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss, correct = 0, 0
    with torch.no_grad():
        for X, y in dataloader:
            X = X.to(device)
            y = y.to(device)
            pred = model(X).to(device)
            test_loss += loss_fn(pred, y).item()
            correct += (pred.argmax(1) == y).type(torch.float).sum().item()

    test_loss /= num_batches
    correct /= size
    print(f"Test Error: \n Accuracy: {(100 * correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

def oooo(learning_rate,epochs,batch_size):
    config_file = 'configs/LLD_config.yaml'
    config = utils.parse_opt(config_file)
    embeddings,label = get_LLDs_dataset_casia(config)
    dataset = torch.utils.data.TensorDataset(F.normalize(torch.tensor(embeddings),dim=0), torch.tensor(label))
    # train, test = torch.utils.data.random_split(dataset, (1000, 200))
    # train_dataloader = DataLoader(train, batch_size=200, shuffle=True)
    # test_dataloader = DataLoader(test, batch_size=200, shuffle=True)
    train_dataloader = DataLoader(dataset, batch_size, shuffle=True)
    test_dataloader = DataLoader(dataset, batch_size, shuffle=True)

    model = LinearNetwork()
    model.to(device)
    # Initialize

    loss_fn = nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

    for t in range(epochs):
        train_loop(dataloader=train_dataloader, model=model, loss_fn=loss_fn, optimizer=optimizer)
        if t%5==0:
            print(f"Epoch {t }\n-------------------------------")
            test_loop(dataloader=test_dataloader, model=model, loss_fn=loss_fn)

    print("Done!")


if __name__ == '__main__':
    config_file = 'configs/LLD_config.yaml'
    config = utils.parse_opt(config_file)
    learning_rate= config.learning_rate
    epochs = config.epochs
    batch_size=config.batch_size
    oooo(learning_rate,epochs,batch_size)




